<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-form ref="form" :model="form" label-width="80px" size="mini" :rules="rules" class="demo-ruleForm">
          <!--          学科-->
          <el-row>
            <el-col :span="8">
              <el-form-item prop="subjectID" label="学科">
                <el-select v-model="form.subjectID" placeholder="请选择"  @change="onSubjectChange">
                  <el-option v-for="(item, index) in subjects" :key="index" :label="item.subjectName" :value="item.id"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          目录-->
          <el-row>
            <el-col :span="8">
              <el-form-item prop="catalogID" label="目录">
                <el-select v-model="form.catalogID" placeholder="请选择" @change="onDirectoryChange">
                  <el-option v-for="(item, index) in directory" :key="index" :label="item.directoryName" :value="item.id"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          企业-->
          <el-row>
            <el-col :span="8">
              <el-form-item  prop="enterpriseID" label="企业">
                <el-select v-model="form.enterpriseID" placeholder="请选择" @change="onDirectoryChange">
                  <el-option v-for="(item, index) in companyList" :key="index" :label="item.company" :value="item.id"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          城市-->
          <el-row>
            <el-col :span="8">
              <el-form-item class="city-box" label-width="120px" prop="province" label="城市：">
                <el-select class="city-1" style="" v-model="form.province" placeholder="请选择"  @change="onProvinceChange">
                  <el-option v-for="(item, index) in province" :key="index" :label="item" :value="item"> </el-option>
                </el-select>
                <el-select class="city-2" v-model="form.city" placeholder="请选择" @change="onDirectoryChange">
                  <el-option v-for="(v, k, i) in citys" :key="i" :label="v" :value="v"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          方向-->
          <el-row>
            <el-col :span="8">
              <el-form-item prop="direction" label="方向">
                <el-select v-model="form.direction" placeholder="请选择活动区域" @change="onDirectoryChange">
                  <el-option v-for="(item, index) in direction" :key="index" :label="item" :value="item"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          题型-->
          <el-row>
            <el-col :span="8">
              <el-form-item label="题型">
                <el-radio v-model="form.questionType" label="1">单选</el-radio>
                <el-radio v-model="form.questionType" label="2">多选</el-radio>
                <el-radio v-model="form.questionType" label="3">简答</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          难度-->
          <el-row>
            <el-col :span="8">
              <el-form-item class="city-box" label-width="120px" label="难度：">
                <el-radio v-model="form.difficulty" label="1">简单</el-radio>
                <el-radio v-model="form.difficulty" label="2">一般</el-radio>
                <el-radio v-model="form.difficulty" label="3">困难</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          题干-->
          <el-row>
            <el-col>
              <el-form-item label-width="120px" prop="question" label="题干：" class="city-box">
                <quill-editor class="quill-editor" ref="myTextEditor" v-model="form.question" style="width:1150px;height:200px;"></quill-editor>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          选项-->
          <!-- 单选 -->
          <template v-if="form.questionType === '1'">
            <div v-for="(item, index) in arr" :key="index">
              <el-row v-if="index < 4">
                <el-col>
                  <el-form-item label-width="120px" label="选项：">
                    <el-row>
                      <el-col :span="1">
                        <el-radio :label="index" v-model="radio">{{ item.code }}：</el-radio>
                      </el-col>
                      <el-col :span="5"> <el-input v-model="item.title"></el-input> </el-col>
                      <el-col :span="10">
                        <el-upload class="upload-demo" action="#" multiple :limit="3">
                          <el-button class="upload_btn">点击上传</el-button>
                        </el-upload>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-row>
              <el-col>
                <el-button class="add_btn" type="danger" size="small" @click="addItem" disabled>+增加选项与答案</el-button>
              </el-col>
            </el-row>
          </template>

          <!-- 多选 -->
          <template v-if="form.questionType === '2'">
            <div v-for="(item, index) in arr" :key="index">
              <el-checkbox-group v-model="checkList">
                <el-row v-if="index < questionIndex">
                  <el-col>
                    <el-form-item label-width="120px" label="选项：">
                      <el-row>
                        <el-col :span="1">
                          <el-checkbox :label="index">{{ item.code }}</el-checkbox>
                        </el-col>
                        <el-col :span="5"> <el-input v-model="item.title"></el-input> </el-col>
                        <el-col :span="10">
                          <el-upload class="upload-demo" action="#" multiple :limit="3">
                            <el-button class="upload_btn">点击上传</el-button>
                          </el-upload>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-checkbox-group>
            </div>
            <el-row>
              <el-col>
                <el-button class="add_btn" type="danger" size="small" @click="addItem">+增加选项与答案</el-button>
              </el-col>
            </el-row>
          </template>
          <!--          视频解析-->
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="120px" label="解析视频：" style="margin-left: 30px">
                <el-input v-model="form.videoURL" style="width: 200px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          答案解析-->
          <el-row>
            <el-col class="right-all">
              <el-form-item label-width="120px" prop="question" label="答案解析：" >
                <quill-editor class="quill-editor" ref="myTextEditor" v-model="form.answer" style="height:200px;width: 1150px; margin-left: 1px"></quill-editor>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          题目备注-->
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="120px" label="题目备注：" class="right-all">
                <el-input type="textarea" :rows="2" resize="none" placeholder="请输入内容" v-model="form.remarks" class="right-all" style="width: 340px"> </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          试题标签-->
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="120px" label="题目标签：" class="right-all">
                <el-select v-model="form.tags" multiple allow-create placeholder="请选择"  class="right-all">
                  <el-option v-for="item in tagList" :key="item.tagName" :label="item.tagName" :value="item.tagName" style="width: 240px"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label-width="120px" label="" style="margin-left: 100px">
            <el-button :type="$route.query.id ? 'success ' : 'primary'" @click="onClick($event)">{{ $route.query.id ? '确认修改' : '确认提交' }}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 富文本引入
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import * as subject from '@/api/hmmm/subjects'
// 学科引入
import * as company from '../../api/hmmm/companys'
import * as tag from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import * as directory from '@/api/hmmm/directorys'
import * as question from '@/api/hmmm/questions'
// console.log('directory' + directory.list)
// console.log(this.setArr())
export default {
  data () {
    return {
      key: 1,
      letter: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
      checkList: [],
      radio: '',
      questionIndex: 4,
      arr: [],
      companyList: [],
      activeName: 'all',
      questionItem: {},
      dialogVisible: false,
      questionList: [],
      citys: [],
      province: provinces(),
      tagList: [],
      userList: [],
      direction: ['o2o', '外包服务', '企业服务', '互联网金融', '企业咨询', '互联网', '电子商务', '其他'],
      difficulty: {
        1: '简单',
        2: '一般',
        3: '困难'
      },
      questionType: {
        1: '单选',
        2: '多选',
        3: '简答'
      },
      directory: [],
      subjects: [],
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [],
        videoURL: ' ',
        answer: '',
        remarks: '',
        tags: []
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科' }],
        catalogID: [{ required: true, message: '请选择目录' }],
        enterpriseID: [{ required: true, message: '请选择企业' }],
        province: [{ required: true, message: '请选择地区' }],
        direction: [{ required: true, message: '请选择方向' }],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, message: '请输入答案解析' }],
        videoURL: [{ required: true, message: '请输入解析视频地址' }]
      }
    }
  },
  methods: {
    async getQuestionsInfo () {
      if (this.$route.query.id) {
        this.setArr()
        const { data: res } = await question.detail({ id: this.$route.query.id })
        // console.log(res + 'id')
        // 数据替换到 form
        this.form = res
        console.log(this.form.tags)
        // 标签改成数组
        try {
          this.form.tags = res.tags.split(',')
        } catch (error) {}
        this.questionIndex = this.form.options.length
        const newArrL = this.form.options.length
        console.log(newArrL)
        const newArr = this.form.options.concat(newArrL)
        console.log(newArr)
        for (let i = 0; i < newArrL; i++) {
          this.arr[i].code = newArr[i].code
          this.arr[i].id = newArr[i].id
          this.arr[i].img = newArr[i].img
          this.arr[i].isRight = newArr[i].isRight
          this.arr[i].questionsID = newArr[i].questionsID
          this.arr[i].title = newArr[i].title
        }
        // 开始获取目录
        const { data } = await directory.list({ subjectID: this.form.subjectID })
        this.directory = data.items

        switch (this.form.questionType) {
          // 单选
          case '1':
            this.form.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.radio = index
              }
            })
            break
          // 多选
          case '2':
            this.form.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.checkList.push(index)
              }
            })
            break
        }
      }
    },

    onClick (e) {
      let optionArr
      let arr
      let data
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return false
        } else {
          switch (e.target.innerText) {
            case '确认提交':
              await this.onSubmit()
              this.$message.success('添加成功')
              break
            case '确认修改':
              // 标签转字符串
              this.form.tags = this.form.tags.join(',')
              // 试题选项操作 处理数据
              switch (this.form.questionType) {
                // 单选
                case '1':
                  optionArr = this.arr.slice(0, 4)
                  // 判断默认勾选
                  optionArr.forEach((item, index) => {
                    item.isRight = index === this.radio
                  })
                  this.form.options = optionArr.reverse()
                  break

                // 多选的情况
                case '2':
                  arr = this.arr.slice(0, this.questionIndex)
                  // 判断默认勾选
                  for (let i = 0; i < arr.length; i++) {
                    this.checkList.forEach(item => {
                      if (i === item) {
                        arr[i].isRight = true
                      }
                    })
                  }
                  this.form.options = arr.reverse()
                  break
              }
              data = await question.update(this.form)
              console.log(data)
              this.$message.success('修改成功')
              break
          }
          await this.$router.push('list')
        }
      })
    },

    // 🌈 提交选项
    async onSubmit () {
      let arr
      // 标签转字符串
      this.form.tags = this.form.tags.join(',')
      let optionArr
      // 试题选项操作 处理数据
      switch (this.form.questionType) {
        // 单选
        case '1':
          optionArr = this.arr.slice(0, 4)
          // 判断默认勾选
          optionArr.forEach((item, index) => {
            item.isRight = index === this.radio
          })
          this.form.options = optionArr
          break

        // 多选的情况
        case '2':
          arr = this.arr.slice(0, this.questionIndex)
          // 判断默认勾选
          for (let i = 0; i < arr.length; i++) {
            this.checkList.forEach(item => {
              if (i === item) {
                arr[i].isRight = true
              }
            })
          }
          this.form.options = arr
          break
      }
      const data = await question.add(this.form)
      console.log(data)
    },
    async onSubjectChange (val) {
      this.form.tags = null
      this.form.catalogID = null
      console.log(directory.list + '目录接口')
      const { data: res } = await directory.list({ subjectID: val })
      this.directory = res.items
      this.tagList = []
    },
    setArr () {
      for (let i = 0; i <= this.letter.length; i++) {
        this.arr.push({
          code: this.letter.charAt(i), // 代码
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否正确答案 true/false
        })
      }
    },
    async getQuestionsList () {
      try {
        const { data: res } = await subject.list({ page: 1, pagesize: 100 })
        this.subjects = res.items
      } catch (error) {}
    },
    async getCompanyList () {
      const { data: res } = await company.list({
        page: 1,
        pagesize: 99
      })
      this.companyList = res.items
    },
    onDirectoryChange () {
      // 获取标签
      this.getTagList()
    },
    addItem () {
      if (this.questionIndex > 25) {
        return
      }
      this.questionIndex++
    },
    onProvinceChange (val) {
      this.form.city = ''
      this.citys = citys(val)
    },
    // 🌈 获取标签列表
    async getTagList () {
      const { data: res } = await tag.list({
        subjectID: this.form.subjectID
      })
      if (res.items.length) {
        this.tagList = res.items
      } else {
        this.tagList = []
      }
    }
  },
  components: {
    quillEditor
  },
  created () {
    this.date = Date.now()
    this.getQuestionsList()
    this.getCompanyList()
    this.getTagList()
    this.getQuestionsInfo()
    this.setArr()
  },
  watch: {
    '$route.query.id' () {
      ++this.key
      this.$router.go(0)
      this.getQuestionsInfo()
    }
  }
}
</script>
<style scoped lang="scss">
.el-form-item__label {
  width: 200px !important;
}
.hr-line {
  color: #ebeef5;
}
.top_title {
  margin: 20px 0 20px 0;
}
.el-card {
  .upload-demo {
    margin-left: 20px;
    .upload_btn {
      margin-top: -10px;
      height: 50px;
    }
  }
  .add_btn {
    margin: 10px 0 20px 120px;
  }
  .el-form {
    margin-top: 30px;
  }
  .city-1 {
    width: 48%;
    margin-right: 4%;
  }
  .city-2 {
    width: 48%;
  }
  margin: 10px;
  padding-bottom: 200px;
  .quill-editor {
    margin-bottom: 60px;
  }
  .right-all{
    margin-right: 28px;
  }
  .left-all{
    margin-left: -28px;
  }
  .city-box{
    //display:flex;
    align-items: center;
    margin-left: -28px;
  }
}
</style>
